<template>
  <el-card>
    <el-button :icon="Plus" type="primary" @click="addDrand" v-has="'btn.Trademark.add'"
      >添加品牌</el-button
    >
    <el-table :data="records" border style="margin: 20px 0">
      <!--      
                data : 要渲染的数据
                el-table-column 一列
                label : 名称
             -->
      <el-table-column
        label="序号"
        type="index"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <!-- 插槽必须template,必须引入v-slot -->
        <template #="{ row, $index }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <!-- 插槽必须template,必须引入v-slot -->
        <template #="{ row, $index }">
          <el-button
            type="warning"
            :icon="Edit"
            @click="addTrademarkPut(row, $index)"
          ></el-button>
          <!-- 删除按钮:气泡确认框 -->
          <el-popconfirm :title="`确定要删除${row.tmName}?`" :icon="Delete" icon-color="red" @confirm="removeTrademark(row.id)">
            <template #reference>
              <el-button type="danger" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--  分页器
        total :总数
        current-page : 当前页数
        page-size  : 每页显示条目个数
        page-sizes  : 数组,每页显示条数组
        small : 小型分页器
        disabled:是否可用
        background : 给分页器按钮添加背景颜色[需要的也是布尔值]

        size-change : 下拉菜单回调
        current-change : 切换页码


     -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      :small="false"
      :disabled="false"
      :background="true"
      layout=" prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="getData"
      prev-text="上"
      next-text="下"
    />
    <!-- 对话框 -->
    <el-dialog
      v-model="outerVisible"
      :title="reqTrademark.id ? '修改品牌' : '添加品牌'"
      draggable
    >
      <!-- from表单 -->
      <el-form
        label-width="100px"
        :model="reqTrademark"
        :rules="verify"
        ref="formVC"
      >
        <!-- 两个item -->
        <el-form-item label="品牌名称" style="width: 80%" prop="tmName">
          <!-- imput框,动态填入到请求数据中 -->
          <el-input v-model="reqTrademark.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 插槽需要加入一个upload -->
          <!-- 
            action:	请求 URL
            show-file-list : 是否显示文件列表
            before-upload :上传文件之前的钩子 参数为上传文件 返回false 或者失败promise 停止上传
           -->
          <el-upload
            class="avatar-uploader"
            action="/app-dev/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <!-- 当前图片有就显示图片,没有显示icon图标 -->
            <img
              v-if="reqTrademark.logoUrl"
              :src="reqTrademark.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="outerVisible = false">取消</el-button>
          <el-button type="primary" @click="reqHandler"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import { ref, onMounted, reactive } from "vue";
// 请求
import {
  reqTardemarkList,
  reqAddTramarkPutTradmark,
  clearTrademark
} from "@/api/product/trademark/index";
// 获取ts类型
import type {
  trademarkArr,
  resTrademark,
  trademark,
} from "../../../api/product/trademark/model/index";
// element-plus ts类型
import type { UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
//当前页数
let currentPage = ref<number>(1);
//当前每页显示条数
let pageSize = ref<number>(5);
//表格的数据---数组
let records = ref<trademarkArr>([]);
//总条数
let total = ref<number>(0);
//切换页码  v-model已经自动收集数据吗,所有不需要写回调,直接调用请求即可
//下拉菜单
let handleSizeChange = () => {
  // 页数归1
  currentPage.value = 1;
  //发请求
  getData();
};
//组件挂载
onMounted(() => {
  getData();
});

//定义添加品牌弹框的状态
let outerVisible = ref<boolean>(false);
//添加品牌按钮的回调函数
let addDrand = () => {
  // 弹框
  outerVisible.value = true;
  // resetFields 函数会将数据回复原始值,所以需要放到前面,恢复完原始值再进行清空
  //清空表单校验提示信息  //能fromVC实例,就可以调用
  formVC.value && formVC.value.resetFields();
  // 清空原有数据
  reqTrademark.id = 0;
  reqTrademark.tmName = "";
  reqTrademark.logoUrl = "";
};

//上传文件成功后的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //将上传成功后的图片远程地址存储到请求数据中
  reqTrademark.logoUrl = response.data;
};
//文件上传前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  //参数为 上传的文件
  //图片类型判断
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    // 图片大小判断 //size 单位 字节
    if (rawFile.size / 1024 / 1024 > 5) {
      // 大于5M
      ElMessage.error("图片内容过大");
      return false;
    } else {
      ElMessage.success("上传成功");
      return true;
    }
  }
  ElMessage.error("图片格式不正确");
  return false;
};

//删除按钮的回调
let removeTrademark = async (id:number) =>{
  try{
    // 请求删除数据
    await clearTrademark(id)
    // 请求成功弹框
    ElMessage({
      message:'删除成功',
      type:'success'
    })
    // 重新获取数据
    getData()
  }catch(e){
// 请求失败弹框
ElMessage({
      message:'删除失败',
      type:'error'
    })
  }
  
} 

//定义ref获取form组件实例
let formVC = ref();
//自定义校验规则
let validator = (validate: any, value: string, callBack: any) => {
  // validate 校验规则对象
  //value 表单输入内容
  // callback  放行函数
  //自定义规则两位以上汉字放行
  if (/^[\u4e00-\u9fa5]{2,}$/.test(value)) {
    callBack();
  } else {
    // 弹出错误
    callBack(new Error("品牌名称-两位以上的汉字"));
  }
};
//校验规则
let verify = {
  tmName: [
    { required: true, message: "品牌名字不能为空", trigger: "blur" },
    // {min:2,max:5, message: "品牌名称2-6位", trigger: "change"}
    { validator: validator, trigger: "change" },
  ],
  logoUrl: [{ required: true, message: "请上传图片" }],
};

//修改按钮的回调
let addTrademarkPut = (row: any, $index: any) => {
  // row: 当前展示数据
  // $index:当前展示数据索引
  //展示dialog对话框
  outerVisible.value = true;
  // 重置表单校验提示信息
  formVC.value && formVC.value.resetFields();
  // 将当前id保存到请求的数据中
  reqTrademark.id = row.id;
  reqTrademark.tmName = row.tmName;
  reqTrademark.logoUrl = row.logoUrl;
};

//点击提交上传按钮的回调
let reqHandler = async () => {
  // 判断当前是否已经有内容
  try {
    // 调用form组件ref对象的validate方法,进行整体表单验证
    await formVC.value.validate(); //返回 promise对象
    // 发请求
    await reqAddTramarkPutTradmark(reqTrademark);
    //弹框
    ElMessage({
      message: reqTrademark.id ? "修改成功" : "添加成功",
      type: "success",
    });
    //关闭弹框
    outerVisible.value = false;
    // 当前操作如果是新增,需要新增完数据回到第一页
    if (!reqTrademark.id) currentPage.value = 1;
    //渲染页面
    getData();
  } catch (e) {
    ElMessage({
      message: reqTrademark.id ? "修改数据失败" : "添加数据失败",
      type: "error",
    });
  }
};
//定义请求数据
let reqTrademark = reactive<trademark>({ tmName: "", logoUrl: "" });

//封装请求
let getData = async () => {
  let result: resTrademark = await reqTardemarkList(
    currentPage.value,
    pageSize.value
  );
  records.value = result.records;
  total.value = result.total;
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>